<?php
session_start();
header("Content-Type:text/html;charset=utf-8");
include_once( 'config.php' );
include_once( 'saetv2.ex.class.php' );
$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
if (isset($_REQUEST['code'])) {
	$keys = array();
	$keys['code'] = $_REQUEST['code'];
	$keys['redirect_uri'] = WB_CALLBACK_URL;
	try {
		$token = $o->getAccessToken( 'code', $keys ) ;
		$time = time()+$token['expires_in'];
	} catch (OAuthException $e) {
	}
}
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD); 
mysql_select_db(DB_NAME,$con);
mysql_query("SET NAMES utf8");
if ($token) {
    $domain = getdomain();
	$_SESSION['token'] = $token;
	setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );  
    echo '授权完成<br />';
    $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
    $uid_get = $c->get_uid();
    $uid = $uid_get['uid'];
    $ms  = $c->home_timeline(); // done
    $user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
    dump($user_message);
    echo $user_message['screen_name'];  
    $sql="select * from cai_uid where uid='".$uid."' and domain='".$domain."'"; 
    $result=mysql_query($sql);
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    if (!mysql_num_rows($result)){
        $sql2="INSERT INTO `cai_uid` (`id`, `uid`, `token` , `name`,`sns`,`expires`,`domain`) VALUES (NULL,'".$uid."','".$_SESSION['token']['access_token']."','".$user_message['screen_name']."','weibo','".$time."','".$domain."');";
        if(mysql_query($sql2)){
            echo "插入成功";
        }else{
            echo "插入成功";
        } 
    }else{
        $sql3="UPDATE `cai_uid` SET `token` =  '".$_SESSION['token']['access_token']."' ,`name` =  '".$user_message['screen_name']."',`expires` =  '".$time."' WHERE  uid='".$uid."';";
        if(mysql_query($sql3)){
            echo "更新成功";
        }else{
            echo "更新失败";
        } 
    }
} else {
    echo "授权失败";
}
echo "<br/><a href ='../shouquan.php'>查看所有授权</a><br/>";
$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
echo '<br/><a href="'.$code_url.'"><img src="../img/weibo.png" title="点击进入授权页面" alt="点击进入授权页面" border="0" /></a>';
function dump($vars, $label = '', $return = false) {
    if (ini_get('html_errors')) {
        $content = "<pre>\n";
        if ($label != '') {
            $content .= "<strong>{$label} :</strong>\n";
        }
        $content .= htmlspecialchars(print_r($vars, true));
        $content .= "\n</pre>\n";
    } else {
        $content = $label . " :\n" . print_r($vars, true);
    }
    if ($return) { return $content; }
    echo $content;
    return null;
}

?>
